package com.applet.dish.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.applet.category.service.CategoryService;
import com.applet.dish.mapper.DishMapper;
import com.applet.dish.service.DishService;
import com.applet.dishflavor.service.DishFlavorService;
import com.applet.entity.Category;
import com.applet.entity.Dish;
import com.applet.entity.DishFlavor;
import com.applet.exception.DishNotFoundException;
import com.applet.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 菜品管理 serviceImpl
 */
@Slf4j
@Service
public class DishServiceImpl implements DishService {

    @Resource
    private DishMapper dishMapper;

    @Resource
    private CategoryService categoryService;

    @Resource
    private DishFlavorService dishFlavorService;



    /**
     * 菜品管理
     * 查询分类id下所有菜品及菜品口味
     *
     * @param categoryId
     */
    @Override
    public List<DishVO> queryDishListAndFlavorByCategoryId(Long categoryId) {
        // 1.查询起售的菜品集合
        List<Dish> dishList = dishMapper.selectDishListByCategoryId(categoryId);
        if (CollectionUtils.isEmpty(dishList)) {
            //菜品为空
            //throw new DishNotFoundException("菜品数据为空");  //小程序未做异常数据接收，不能抛出异常
            return new ArrayList<>();
        }
        // 2.封装返回值对象 属性拷贝
        List<DishVO> dishVOList = dishList.stream().map((dish) -> JSON.parseObject(JSON.toJSONString(dish, SerializerFeature.WriteMapNullValue), DishVO.class)).collect(Collectors.toList());
        // 3.封装菜品分类名称  ==> 这些菜品的categoryId都相同，属于同一个分类下，查询一次即可
        Category category = categoryService.selectCategoryById(dishVOList.get(0).getCategoryId());
        if(Objects.nonNull(category)){
            dishVOList.forEach(dishVO -> dishVO.setCategoryName(category.getName()));
        }
        // 4.封装菜品口味
        for (DishVO dishVO : dishVOList) {
            List<DishFlavor> dishFlavorList = dishFlavorService.selectDishFlavorListByDishId(dishVO.getId());
            if( !CollectionUtils.isEmpty(dishFlavorList) ){
                dishVO.setFlavors(dishFlavorList);
            }
        }
        // 5.返回
        return dishVOList;
    }



    /**
     * 菜品管理
     *        根据id查询菜品
     * @param id
     */
    @Override
    public Dish selectDishById(Long id) {
        return dishMapper.selectDishById(id);
    }


}
